import Day from "./Day";
import dayjs from "dayjs";
import MonthPane from "./MonthPane";
import { DatepickerStore } from ".";
import { PropType, computed, defineComponent, inject, ref } from "vue";
import { FeatherChevronLeft, FeatherChevronRight, FeatherChevronsLeft, FeatherChevronsRight } from "cui-vue-icons/feather";

const weeks = ['日', '一', '二', '三', '四', '五', '六'];
export function clearHms (date: Date): Date {
    date.setHours(0);
    date.setMinutes(0);
    date.setSeconds(0);
    date.setMilliseconds(0);
    return date;
}

const changeCurrentMonth = (store: DatepickerStore,
    type: 'Month'|'FullYear', name: string, op: number, stick: boolean) => {
    const month = store.currentMonth[name === 'end' ? 1 : 0];
    month[`set${type}`](month[`get${type}`]() + 1 * op);
    const newMonth = [...store.currentMonth];
    if (stick) {
        const other = newMonth[name === 'end' ? 0 : 1];
        other[`set${type}`](other[`get${type}`]() + 1 * op);
    } else {
        if (dayjs(newMonth[0]).format('YYYY-MM') === dayjs(newMonth[1]).format('YYYY-MM')
            || newMonth[0].getTime() > newMonth[1].getTime()) {
            const other = newMonth[name === 'end' ? 0 : 1];
            other[`set${type}`](other[`get${type}`]() + 1 * op);
        }
    }
    store.currentMonth = newMonth;
};

export default defineComponent({
    name: 'DatePane',
    props: {
        name: String,
        value: [String, Object],
    },
    setup (props) {
        const ctx = inject('CMDatepickerContext', null);
        const store = ctx.store;
        const type = ctx.type ?? 'date';
        const view = ref('date');
        const onNextMonth = () => {
            changeCurrentMonth(store, 'Month', props.name, 1, ctx.stick);
        };

        const onPrevMonth = () => {
            changeCurrentMonth(store, 'Month', props.name, -1, ctx.stick);
        };

        const onPrevYear = () => {
            changeCurrentMonth(store, 'FullYear', props.name, -1, ctx.stick);
        };

        const onNextYear = () => {
            changeCurrentMonth(store, 'FullYear', props.name, 1, ctx.stick);
        };

        const onShowMonthView = () => {
            view.value = 'month';
        };

        const onBack = () => {
            view.value = 'date';
        };

        const onMonthChange = (date: Date, type: 'year'|'month', name: string) => {
            const month:Date = store.currentMonth[name === 'end' ? 1 : 0];
            month.setFullYear(date.getFullYear());
            month.setMonth(date.getMonth());
            const newMonth = [...store.currentMonth];
            const method = type === 'year' ? 'FullYear' : 'Month';
            if (ctx.stick) {
                const other = new Date(month);
                other.setMonth(other.getMonth() + 1 * (name === 'end' ? -1 : 1));
                newMonth[name === 'end' ? 0 : 1] = other;
            } else {
                if (dayjs(newMonth[0]).format('YYYY-MM') === dayjs(newMonth[1]).format('YYYY-MM')
                    || newMonth[0].getTime() > newMonth[1].getTime()) {
                    const other = newMonth[name === 'end' ? 0 : 1];
                    other[`set${method}`](other[`get${method}`]() + 1 * (name === 'end' ? -1 : 1));
                }
            }
            store.currentMonth = newMonth;
        };

        const days = () => {
            const rets = [];
            const first = clearHms(new Date(store.currentMonth[props.name === 'end' ? 1 : 0]));

            first.setDate(1);
            const last = new Date(first);
            last.setMonth(last.getMonth() + 1);
            last.setDate(0);

            // 当月第一天是星期几，前面空几个格子
            const index = first.getDay() % 7;
            const start = new Date(first);
            start.setDate(start.getDate() - index - 1);
            for (let i = 0; i < index; i++) {
                rets.push(new Date(start.setDate(start.getDate() + 1)));
            }

            first.setDate(0);
            for (let i = 0; i < last.getDate(); i++) {
                rets.push(new Date(first.setDate(first.getDate() + 1)));
            }

            let end: any = rets[rets.length - 1];
            end = new Date(end);
            for (let i = 0, j: number = 42 - rets.length; i < j; i++) {
                rets.push(new Date(end.setDate(end.getDate() + 1)));
            }

            return rets;
        };

        const text = computed(() => {
            return dayjs(store.currentMonth[props.name === 'end' ? 1 : 0]).format('YYYY年MM月');
        });

        return () => <div class="cm-date-picker-date">
            {
                view.value === 'date'
                    ? <div class="cm-date-picker-date-inner">
                        <div class="cm-date-picker-date-header">
                            <div class="cm-date-picker-header-arrow">
                                <FeatherChevronsLeft onClick={onPrevYear}/>
                            </div>
                            <div class="cm-date-picker-header-arrow">
                                <FeatherChevronLeft onClick={onPrevMonth}/>
                            </div>
                            <span class="cm-date-picker-date-info" onClick={onShowMonthView}>{text.value}</span>
                            <div class="cm-date-picker-header-arrow">
                                <FeatherChevronRight onClick={onNextMonth}/>
                            </div>
                            <div class="cm-date-picker-header-arrow">
                                <FeatherChevronsRight onClick={onNextYear}/>
                            </div>
                        </div>
                        <div class="cm-date-picker-date-body">
                            <div class="cm-date-picker-week-line">
                                {
                                    weeks.map(item => {
                                        return <div>{item}</div>;
                                    })
                                }
                            </div>
                            <div class="cm-date-picker-date-days">
                                {
                                    days().map(day => {
                                        return <Day range={store.range} hoverDate={store.hoverDate} type={type}
                                            day={day} value={props.value} name={props.name} month={store.currentMonth[props.name === 'end' ? 1 : 0]}/>;
                                    })
                                }
                            </div>
                        </div>
                        <div class="cm-date-picker-date-footer"></div>
                    </div>
                    : null
            }
            {
                view.value === 'month'
                    ? <MonthPane name={props.name} onBack={onBack} onMonthChange={onMonthChange}/>
                    : null
            }
        </div>;
    }
});
